<template>
    <div class="flex flex-row box-border h-full">
        <section class="flex-none box-border flex flex-col w-[224px] border-r border-solid border-r-[#E8EBF5]">
            <ul class="flex flex-col gap-[10px] box-border h-full px-6 py-5 overflow-auto flex-1">
                <li v-for="dep of depOptions" :key="dep.value"
                    :class="dep.value === formState.departmentId ? 'arbitraryactive' : ''"
                    @click="handleDepChange(dep)"
                    class="flex flex-row items-center justify-between box-border cursor-pointer h-10 text-sm text-third arbitrary">
                    <span>{{ dep.label }}</span>
                    <a-dropdown>
                        <template #overlay>
                            <a-menu @click="handleActonDep(dep, $event)">
                                <a-menu-item key="edit">
                                    编辑
                                </a-menu-item>
                                <a-menu-item key="delete">
                                    删除
                                </a-menu-item>
                            </a-menu>
                        </template>
                        <GpFontIcon v-if="dep.value !== AllValue" name="icon-gengduo1" class="hover:text-theme !text-xl cursor-pointer" @click.stop />
                    </a-dropdown>
                </li>
            </ul>
            <div @click="handleDepTriggerAction('create', null)"
                class="flex-none box-border flex flex-row justify-center items-center touchable-opacity h-15 border-t border-solid border-t-[#E8EBF5] bg-[#FBFCFF] text-theme">
                <GpFontIcon name="icon-tianjia" />
                添加部门
            </div>
        </section>
        <section class="flex-1 pt-5 flex flex-col box-border overflow-hidden">
            <div class="flex-none box-border px-6 pb-6">
                <a-flex :gap="12" justify="space-between">
                <a-flex :gap="12" wrap="wrap">
                    <GpFormField label="成员姓名" style="width: 250px;" #default="{style, props}">
                        <a-input placeholder="请输入姓名" size="large" v-model:value="formState.name"
                            :style="style" v-bind="props" class="!h-10"/>
                    </GpFormField>
                    <GpFormField label="账号状态" style="width: 250px;" #default="{style, props}">
                        <a-select placeholder="请选择状态" size="large" v-model:value="formState.isLock"
                            :options="statusOptions" :style="style" v-bind="props"/>
                    </GpFormField>
                    <a-button ghost type="primary" @click="refresh()" size="large">查询</a-button>
                </a-flex>
                <a-flex :gap="12" wrap="nowrap">
                    <a-button type="primary" size="large" @click="openInvite()">
                        <template #icon>
                            <GpFontIcon name="icon-yaoqing" />
                        </template>
                        邀请成员
                    </a-button>
                    <a-button type="primary" size="large" @click="handleTriggerAction('create', null)">
                        <template #icon>
                            <GpFontIcon name="icon-tianjia" />
                        </template>
                        添加成员
                    </a-button>
                </a-flex>
                </a-flex>
            </div>
            <div class="flex-1 px-6 box-border overflow-auto">
                <Table v-bind="defaultTableProps" :columns="columns" :data-source="dataSource" :loading="loading"
                    :pagination="false" :row-selection="rowSelection" @change="handleTableChange">
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.dataIndex === 'department'">
                            {{ [record.departmentName, record.position].join(' - ') }}
                        </template>
                        <template v-else-if="column.dataIndex === 'isAdmin'">
                            {{ record.isAdmin ? '管理员' : '普通成员' }}
                        </template>
                        <template v-else-if="column.dataIndex === 'isLock'">
                            <div class="flex flex-row items-center gap-2">
                                <div class="box-border size-[6px] rounded-full"
                                    :class="record.isLock ? 'text-[#ACAEB2]' : 'text-[#3BBD40]'"></div>
                                <span>{{ record.isLock ? '冻结' : '正常' }}</span>
                            </div>
                        </template>
                        <template v-else-if="column.dataIndex === 'action'">
                            <a-space size="large">
                                <a-button class="!p-0" type="link" @click="handleTriggerAction('update', record as any)">
                                    编辑
                                </a-button>
                                <a-button class="!p-0" type="link" @click="handleUnbind(record.id)" danger>
                                    删除
                                </a-button>
                            </a-space>
                        </template>
                    </template>
                </Table>
            </div>
            <div
                class="flex-none box-border border-t border-solid border-t-[#E8EBF5] flex flex-row items-center pl-[44px] pr-6 h-15">
                <a-dropdown :trigger="['click']">
                    <a-button>批量操作</a-button>
                    <template #overlay>
                        <a-menu @click="handleBatchMenuClick">
                            <a-menu-item key="unbind">
                                <span class="text-primary text-sm">解绑</span>
                            </a-menu-item>
                        </a-menu>
                    </template>
                </a-dropdown>
                <a-pagination class="!ml-auto" :current="pagination.current" :pageSize="pagination.pageSize"
                    show-quick-jumper :total="total" show-less-items show-size-changer
                    @change="handlePaginationChange" />
            </div>
        </section>
        <!-- 编辑/添加公司成员 -->
        <a-modal v-bind="defaultModalProps" :title="triggerAction === 'update' ? '编辑成员' : '添加成员'" v-model:open="showActionPopup" @ok="handleSubmit"
            :ok-button-props="{ loading: formLoading }" :body-style="{paddingBlock: '24px'}">
            <Form hide-required-mark ref="formRef" :model="actionFormState" :rules="rules" :colon="false" size="large"
                class="py-24 px-16">
                <FormItem name="name" label="成员姓名">
                    <a-input v-model:value="actionFormState.name" placeholder="请输入姓名" />
                </FormItem>
                <FormItem name="mobile" label="手机号码">
                    <a-input v-model:value="actionFormState.mobile" placeholder="请输入手机号" :disabled="triggerAction === 'update' && typeof actionEntry?.memberId !== 'undefined' && actionEntry.memberId > 0" />
                </FormItem>
                <FormItem name="departmentId" label="所属部门">
                    <a-select v-model:value="actionFormState.departmentId" :options="departments"
                        placeholder="请选择部门" />
                </FormItem>
                <FormItem name="position">
                    <template #label>
                        <span><span class="invisible">占位</span>职位</span>
                    </template>
                    <a-input v-model:value="actionFormState.position" placeholder="请输入职位" />
                </FormItem>
                <FormItem name="isAdmin" label="账号角色">
                    <a-select v-model:value="actionFormState.isAdmin" :options="roleOptions" placeholder="请选择角色" />
                </FormItem>
            </Form>
        </a-modal>
        <!-- success modal -->
        <a-modal v-bind="defaultModalProps" v-model:open="showActionSuccess" :width="364" :title="null" @cancel="closeActionSuccess">
            <div class="flex flex-row items-center justify-center gap-2">
                <img src="/images/success-check.png" alt="" :width="28" :height="28" class="size-[28px] object-cover block" />
                <span class="text-[#324366] text-2xl font-bold">添加成功</span>
            </div>
            <div class="bg-[#F4F6FC] mt-6 px-10 rounded-sm box-border h-[128px] flex flex-col gap-[14px] justify-center">
                <div class="flex flex-row items-center gap-8 text-sm">
                    <span class="text-[#324366]">成员姓名</span>
                    <span class="text-primary font-medium">{{successInfo.name}}</span>
                </div>
                <div class="flex flex-row items-center gap-8 text-sm">
                    <span class="text-[#324366]">所属部门</span>
                    <span class="text-primary font-medium">{{successInfo.departmentName}}</span>
                </div>
                <div class="flex flex-row items-center gap-8 text-sm">
                    <span class="text-[#324366]">账号角色</span>
                    <span class="text-primary font-medium">{{successInfo.roleName}}</span>
                </div>
            </div>
            <template #footer>
                <a-button type="primary" size="large" block @click="closeActionSuccess">
                    确定
                </a-button>
            </template>
        </a-modal>
        <!-- 添加、编辑部门 -->
        <a-modal v-bind="defaultModalProps" v-model:open="showActionDep" :title="isUpdateDep ? '编辑部门' : '添加部门'"
            :confirm-loading="actionDepLoading" :body-style="{paddingBlockStart: '32px'}"
            @ok="handleActionDepSubmit"
        >
            <Form hide-required-mark :colon="false" ref="depFormRef" :model="actionDepState" :rules="depRules" size="large">
                <FormItem name="name" label="部门名称">
                    <a-input placeholder="请输入部门名称" v-model:value="actionDepState.name"/>
                </FormItem>
            </Form>
        </a-modal>
        <!-- 邀请成员 -->
        <a-modal v-bind="defaultModalProps" v-model:open="showInvite" :footer="null" title="邀请成员" :width="628" :body-style="{paddingBlock: '32px'}">
            <ul class="flex flex-col gap-8 box-border">
                <li class="box-border">
                    <div class="text-sm text-primary mb-[10px]">邀请码</div>
                    <div class="flex flex-row items-center box-border h-[104px] px-6 gap-5 bg-[#F4F6FC]">
                        <div class="flex-1 text-[#324366] text-sm text-justify break-all">{{ inviteInfo?.inviteCode }}</div>
                        <a-button type="primary" @click="copy(inviteInfo?.inviteCode)">
                            复制邀请码
                        </a-button>
                    </div>
                </li>
                <li class="box-border">
                    <div class="text-sm text-primary mb-[10px]">邀请注册链接</div>
                    <div class="flex flex-row items-center box-border h-[104px] px-6 gap-5 bg-[#F4F6FC]">
                        <div class="flex-1 text-[#324366] text-sm text-justify break-all">{{ inviteInfo?.inviteUrl }}</div>
                        <a-button type="primary" @click="copy(inviteInfo?.inviteUrl)">
                            复制链接
                        </a-button>
                    </div>
                </li>
            </ul>
        </a-modal>
    </div>
</template>
<script lang="ts" setup>
import { message, Modal, Table, type MenuProps, Form, FormItem } from 'ant-design-vue';
import { defaultTableProps } from '@/constants/comp-setting';
import { AllValue } from '@/constants/enum-options';
import { columns } from './data';
import { postUserDeletebatch, postUserUserlist } from '@/api/siderBar/user';
import type { UserSearchRequest, UserSearchRequestPageSearchRequest } from '@/api/siderBar/model';
import { useActionEmployee } from './composables/useActionEmployee';
import { useActionDep } from './composables/useActionDep';
import { useInviteMember } from './composables/useInviteMember';
import { defaultModalProps } from '@/constants/comp-setting';
defineOptions({
    name: 'MemberManagePage'
})
definePage({
    name: 'MemberManagePage',
    meta: {
        text: '成员管理',
        title: '成员管理',
        isLayout: false
    }
})
interface IFormState extends UserSearchRequest { }
const { copy } = useCopy()
const formState = ref<IFormState>(getInitialState());
const statusOptions: IOption<boolean>[] = [
    { value: false, label: '正常' },
    { value: true, label: '冻结' },
]
function handleActonDep(dep: IOption<number>, e: any) {
    if (e.key === "edit") {
        handleDepTriggerAction('update', {
            departmentId: dep.value,
            departmentName: dep.label
        })
    } else if (e.key === "delete") {
        deleteDep(dep.value)
    }
}
function handleDepChange(dep: IOption<number>) {
    formState.value.departmentId = dep.value
    refresh()
}
const { rowSelection } = useRowSelection();
const { dataSource, handleTableChange, loading, pagination, refresh, total, handlePaginationChange } =
    useTablePaginationRequest(formState, postReviewGridFetcher);
function postReviewGridFetcher(
    data: UserSearchRequestPageSearchRequest,
) {
    const search = Object.assign({}, data.search)
    if (search.departmentId === AllValue) {
        delete search.departmentId
    }
    return postUserUserlist({
        ...data,
        search,
    }).then(res => normalizePaginationData(res, { current: data.page.pageIndex, pageSize: data.page.pageSize }));
}
function getInitialState(): IFormState {
    return {
        departmentId: AllValue
    }
}
const handleBatchMenuClick: MenuProps['onClick'] = e => {
    if (e.key === "unbind") {
        handleBatchUnbind()
    }
};
function handleBatchUnbind() {
    if (!rowSelection.value || rowSelection.value.selectedRowKeys?.length === 0) {
        message.warn("请先选择要批量操作的项目")
        return
    }
    const ids = <number[]>rowSelection.value.selectedRowKeys
    Modal.confirm({
        title: '确认提示',
        content: '再次确认是否要进行解绑？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
            return postUserDeletebatch({ ids }).then(() => {
                message.success('操作成功')
                refresh()
            })
        },
    })
}
const {
    formRef,
    formState: actionFormState,
    handleSubmit,
    handleTriggerAction,
    roleOptions,
    rules,
    showActionPopup,
    triggerAction,
    departments,
    refreshDeps,
    formLoading,
    handleUnbind,
    actionEntry,
    // success modal
    closeActionSuccess,
    showActionSuccess,
    successInfo
} = useActionEmployee(refresh)
const depOptions = computed<IOption<number>[]>(() => {
    const options: IOption<number>[] = [
        { value: AllValue, label: '全部' }
    ]
    if (departments.value) {
        departments.value.forEach(dep => {
            options.push({
                value: dep.value,
                label: dep.label!
            })
        })
    }
    return options
})
const {
    inviteInfo,
    openInvite,
    showInvite
} = useInviteMember()
const {
    showActionDep,
    rules: depRules,
    formRef: depFormRef,
    formLoading: actionDepLoading,
    formState: actionDepState,
    handleSubmit: handleActionDepSubmit,
    handleTriggerAction: handleDepTriggerAction,
    isUpdate: isUpdateDep,
    deleteDep
} = useActionDep(refreshDeps)
</script>
<style lang="less" scoped>
.arbitrary {
    padding-inline-start: 20px;
    padding-inline-end: 10px;

    &:hover,
    &.arbitraryactive {
        background-color: #F8F9FF;
    }

    &.arbitraryactive {
        font-weight: 500;
        color: #324366;
    }
}
</style>